const Router = require('koa-router');
const {db, Op,QueryTypes } = require("../../models/db");
const tool = require("../../tools/tool");
const {setBillNo, saveHistPrice,setInvoiceGoods} = require("../bill/base");
const tools = require("../../tools/tool");
const router = new Router();
// 提交购物车
router.post('/zd/saveOrder', async ctx => {
    try {
        let user = ctx.user;
        let uid = user.id;
        let tenantId = user.tenantId;
        let contact = await db.models['contact'].findOne({
            where: {
                tenantId,
                id: user.buId
            }
        })
        if(!contact) return ctx.err('终端信息还没录入')
        let cart = ctx.request.body.cart;
        let subRemark = []
        cart.map(row => {
            if(row.remark) subRemark.push(row.remark)
        })
        let carts = []
        for (let i = 0; i < cart.length; i++) {
            if(cart[i].cartId) {
                carts.push(cart[i].cartId)
            }
        }
        let salesId = uid
        let sal = await db.query(`select top 1 salesId from invoice where tenantId=${tenantId} and transType=150601 and buId=${contact.id} and isnull(salesId,0) <>0 order by id desc `,{
            type: QueryTypes.SELECT,plain: true
        })
        if(sal) {
            salesId = sal.salesId
        }
        let invoice = db.models['invoice'].build()
        invoice.billNo = await setBillNo(tenantId, 150601);
        invoice.tenantId = tenantId
        invoice.printNo = 0
        invoice.transType = 150601
        invoice.billState = 'draft'
        invoice.transTypeName = '销售单'
        invoice.orgin = 'zd'
        invoice.billType = 'SALE'
        invoice.salesId = salesId
        invoice.cby = uid
        invoice.buId = contact.id
        invoice.createdAt = tool.getTime();
        invoice.billDate = tool.getDay();
        invoice.totalAmount = tool.xe.sum(cart, 'amount')
        invoice.totalDiscount = 0
        invoice.amount = tool.xe.sum(cart, 'amount')
        invoice.disAmount = 0
        invoice.rpAmount = 0
        invoice.ysAmount = 0
        invoice.hxAmount = 0
        invoice.yhAmount = 0
        invoice.leftAmount = invoice.amount
        invoice.arrears = invoice.amount
        invoice.subRemark = subRemark.join(',')
        invoice.byCell = 1
        let units = await tool.getUnits()
        for (let i = 0; i < cart.length; i++) {
            let row = cart[i]
            let qty = tool.xe.multiply(row.qty,row.calNum)
            if(qty.toString().indexOf('.') !== -1) {
                return ctx.err(`${row.invName} 最小单位数量不能为小数`)
            }
            units.map(unit => {
                if(unit.name === row.unit) {
                    row.unitId = unit.id
                }
            })

            row.price = tool.xe.toNumber(row.price)
            row.tenantId = tenantId
            row.billNo = invoice.billNo
            row.transType = invoice.transType
            row.buId = invoice.buId
            row.deduction = tool.xe.toNumber(row.deduction)
            if(invoice.transType === 150601) {
                if(!row.price) {
                    if(!row.send && !row.remark) {
                        return ctx.err('单价为 0 必须要有备注 或 选择赠品')
                    }
                }
            }
            row.invName = row.name
            row.assQty = tool.calAssQty(row.qty,row.spec,row.unit1, row.unit2)
        }
        let ret = await db.transaction(async () => {
            let invo = await invoice.save()
            if(invo) {
                cart.map(row => {
                    row.iid = invo.id
                    delete row.id
                })
            }
            await db.models['invoiceInfo'].bulkCreate(cart);

            let obj = Object.assign({}, invo)
            obj.infos = cart
            await tools.saveLogInvoice(tenantId, uid, invo.id,  '新增', obj);
            // 删除购物车
            await db.query(`delete from cart_zd  where tenantId=${tenantId} and id in(${carts.join(',')})`, {type: QueryTypes.DELETE})

            await setInvoiceGoods(tenantId, invo.id)

            return invo
        })
        if(ret) {
            let roomId = ctx.roomId
            if(roomId) {
                setTimeout(async () => {
                    let msg = '新增 终端自助下单'
                    ctx.io.to(roomId).emit('appBillAdd', msg)
                }, 300)
            }
        }

        return ctx.suc('订单提交成功', ret)
    } catch (e) {
        return ctx.err(e)
    }
})

module.exports = router;
